<template>
  <div>
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>发布博客</span>
        </div>
      </template>
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        status-icon
        :rules="rules"
        label-width="80px"
        class="login-form"
        label-position="top"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="ruleForm.title" />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select v-model="ruleForm.category" class="m-2" placeholder="请选择至少一项分类" size="large">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="标签" prop="tags">
          <div v-for="tag in tags" :key="tag" >
            <el-tag              
              class="mx-1"
              closable
              :disable-transitions="false"
              @close="handleClose(tag)"
            >
              {{ tag }}
            </el-tag>
          </div>
          <el-col v-if="inputVisible" :span="3.2">
            <el-input
              ref="InputRef"
              v-model="inputValue"
              class="ml-1 w-20"
              size="small"
              @keyup.enter="handleInputConfirm"
              @blur="handleInputConfirm"
              maxlength="18"
            />
          </el-col>
          <el-col v-else :span="3.2">
            <el-button class="button-new-tag ml-1" size="small" @click="showInput">
              + New Tag
            </el-button>
          </el-col>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <div>
            <QuillEditor ref="myQuillEditor" 
              theme="snow" 
              placeholder="请输入内容"
              v-model:content="ruleForm.content"
              :options="editorOption" 
              content-type="html"
            />
          </div>
        </el-form-item>
        <el-button id="submit-btn" type="primary" plain round @click="submitForm()">Submit</el-button>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import api from '../../api/data.js'
import hljs from 'highlight.js';
//import 'highlight.js/styles/default.css'
import 'highlight.js/styles/intellij-light.css'
import { QuillEditor } from '@vueup/vue-quill'
import { ElMessage } from 'element-plus'
import {nextTick} from 'vue'
export default {
  name: 'BlogPublish',
  components: {
    QuillEditor
  },
  data () {
    let validateTitle = (rule, value, callback) => {
      const reg = /^[a-zA-Z0-9\u4e00-\u9fa5]{1,50}$/
      if (value === '') {
        callback(new Error('请输入标题'))
      } else if (!reg.test(value)) {
        callback(new Error('标题过长或格式有误'))
      } else {
        callback()
      }
    }
    let validateCategory = (rule, value, callback) => {
      // const reg = /^[a-zA-Z0-9]{4,10}$/
      if (value === '') {
        callback(new Error('请选择分类'))
      } else {
        callback()
      }
    }
    return {
      editorOption: {
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            // [{'size': ['small', false, 'large', 'huge']}],
            // [{'font': []}],
            ["blockquote", "code-block"], // 引用  代码块
            [{'align': []}],
            [{'list': 'ordered'}, {'list': 'bullet'}],
            // [{'indent': '-1'}, {'indent': '+1'}],
            [{'header': 1}, {'header': 2}], 
            // ['image'],
            // [{'direction': 'rtl' }],    //文字编辑方向，从左到右还是从右到左
            [{ 'color': [] }, { 'background': [] }],
            ["link", "image"],
            ["clean"], // 清除文本格式
          ],
          syntax:{
            //语法高亮
            highlight:text =>{
              //console.log(hljs.highlightAuto(text).value );
              //this.ruleForm.content = hljs.highlightAuto(text).value 
              //console.log(this.ruleForm.content);
              var index = this.ruleForm.content.lastIndexOf('<pre class="ql-syntax" spellcheck="false">');
              this.ruleForm.content = this.ruleForm.content.substring(0,index)+'<pre class="ql-syntax" spellcheck="false">'+hljs.highlightAuto(text).value +'</pre>'
              return hljs.highlightAuto(text).value 
            }
          }
        },
        syntax: true, //语法检测
      },
      inputVisible: false,
      inputValue: '',
      options: [
        {
          label: '前沿技术',
          value: '前沿技术'
        },
        {
          label: '每日刷题',
          value: '每日刷题'
        },
        {
          label: '论文解读',
          value: '论文解读'
        },
        {
          label: '心情随笔',
          value: '心情随笔'
        },
      ],
      tags: [],
      ruleForm: {
        token: '',
        title: '',
        category: '',
        tagList: '',
        content: '',
      },
      rules: {
        title: [
          { validator: validateTitle, trigger: 'blur' }
        ],
        category: [
          { validator: validateCategory, trigger: 'blur' }
        ],
      }
  }},
  methods: {
    handleClose (tag) {
      this.tags.splice(this.tags.indexOf(tag), 1)
    },
    showInput () {
      if (this.tags.length < 4) {
        this.inputVisible = true
        nextTick(() => {
          this.$refs.InputRef.input.focus()
        })
      } else {
        ElMessage.error('最多只能创建4个tag！')
      }
    },
    handleInputConfirm () {
      if (this.inputValue) {
        this.tags.push(this.inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
      // console.log(this.tags)
    },
    submitForm() {
      if (!this.$refs.ruleFormRef) return
      this.ruleForm.token = this.$store.state.token
      this.ruleForm.tagList = this.tags.join('|')
      // console.log(this.ruleForm.tagList)
      if (this.ruleForm.tagList === '') {
        ElMessage.error('至少输入一个tag')
        return
      }
      this.$refs.ruleFormRef.validate((valid) => {
        // console.log(valid)
        // console.log(this.ruleForm.content)
        if (valid) {
          api.publishArticle(
            this.ruleForm
          ).then((res) => {
            if (res.code === 342) {
              this.$store.commit('logout')
              this.$store.commit('tokenError')
              this.$router.push({path: '/login'})
            } else if (res.code < 300) {
              ElMessage({
                message: res.message,
                type: 'success',
              })
              let temp = setInterval(() => {
                this.$router.push({path:'/home'})
                clearInterval(temp)
              }, 1500)
            } else {
              ElMessage.error(res.message)
            }
          })
        } else {
          ElMessage.error('error submit!')
          return false;
        }
      });
    },
  },
  mounted () {
    
  }
}
</script>

<style scoped>
.box-card {
  margin-left: 25vw;
  width: 50vw;
}
</style>
